using System;
using System.Collections.Generic;
using System.ComponentModel;
using DictToObject.Helpers;

namespace DictToObject.FieldExpectations
{
    public class RequiredFieldExpectation : IRequiredFieldExpectation
    {
        private readonly string key;
        private readonly IFieldLikeMember member;
        private bool allowNullOrEmpty;

        public RequiredFieldExpectation(string key, IFieldLikeMember member)
        {
            this.key = key;
            this.member = member;
            allowNullOrEmpty = false;
        }

        public void Apply(object result, IDictionary<string, string> values)
        {
            string value = values[key];
            if (!allowNullOrEmpty && string.IsNullOrEmpty(value))
                throw new InvalidOperationException(string.Format("Null or empty value for key {0} not allowed", key));
            object convertedValue = ConvertValue(value);
            member.SetValue(result, convertedValue);
        }

        private object ConvertValue(string value)
        {
            return member.Type == typeof (string) ? value : TypeDescriptor.GetConverter(member.Type).ConvertFrom(value);
        }

        public void AllowNullOrEmpty()
        {
            allowNullOrEmpty = true;
        }
    }
}